from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from .models import Create, Category

def index_view(request):
    """
    首页故事列表视图
    """
    # 获取所有故事，按创建时间倒序排列
    stories_list = Create.objects.all().order_by('-id')
    # 获取所有分类
    categories = Category.objects.all()
    
    # 分页处理，每页显示6个故事
    paginator = Paginator(stories_list, 6)
    page_number = request.GET.get('page')
    stories = paginator.get_page(page_number)
    
    context = {
        'stories': stories,
        'categories': categories,
    }
    return render(request, 'stories/index.html', context)

def generate_view(request):
    """
    故事生成页面视图
    """
    if request.method == 'POST':
        # 处理故事生成请求
        keywords = request.POST.get('keywords', '')
        genre = request.POST.get('genre', '')
        
        # 这里应该调用AI生成故事的逻辑
        # 目前我们返回一个模拟的故事
        story_content = f"这是一个根据关键词'{keywords}'和类型'{genre}'生成的故事。"
        story_title = f"{keywords}的故事"
        
        return JsonResponse({
            'success': True,
            'title': story_title,
            'content': story_content
        })
    
    return render(request, 'stories/generate.html')

def story_detail_view(request, story_id):
    """
    故事详情视图
    """
    story = get_object_or_404(Create, id=story_id)
    return render(request, 'stories/detail.html', {'story': story})